package com.zf.yichat.api.controller.group;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ServiceException;
import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.dto.request.GroupGagUserRequest;
import com.zf.yichat.api.dto.resp.GroupGagUserDto;
import com.zf.yichat.dto.GroupManageDto;
import com.zf.yichat.model.*;
import com.zf.yichat.service.*;
import com.zf.yichat.service.config.GroupGagService;
import com.zf.yichat.service.config.RongCloudApplication;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.AesUtil;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.common.OKHttpUtil;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 14:12 2019/6/17 2019
 */
@RestController
@RequestMapping("group")
@Slf4j
public class GroupController extends BaseController {

    @Autowired
    private GroupService groupService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private AppNoticeService appNoticeService;

    @Autowired
    private UserService userService;

    @Autowired
    private PacketService packetService;


    @Autowired
    private GroupGagService groupGagService;

    @Autowired
    private RongCloudApplication rongCloudApplication;

    @Value("${st.im_uri}")
    private String imUri;

    /**
     * 禁言指定群成员
     * @return
     */
    @RequestMapping("user/gag/add")
    @ResponseBody
    public FsResponse addGagUser(@RequestBody GroupGagUserRequest request) {
        try {
             HttpPost httpPost = rongCloudApplication.imConstructor("group/user/gag/add");

            String userId = request.getUserId();
            if (StringUtils.isBlank(userId)) {
                return FsResponseGen.failMsg("参数错误，userId为NULL");
            }

            Long decodeGroupId = N3d.decode(request.getGroupId());
            Long decodeUserId = N3d.decode(userId);
             // 查询当前登录用户是都是群组管理者

            String path = imUri + "group/hasManagerRole";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("groupId", decodeGroupId);
            jsonObject.put("memberId", getUserId());
            jsonObject.put("memberId3", "");
            jsonObject.put("memberId4", "2444");
             String resp = OKHttpUtil.httpPostJson(path, jsonObject.toJSONString(), commonHeader());

            JSONObject fsResponse = JSONObject.parseObject(resp);
            String code = fsResponse.getString("code");
            String result = fsResponse.getString("result");

            if (!"200".equals(code)){
                String msg = fsResponse.getString("message");

                return FsResponseGen.failMsg(msg);
            }
            if (result.equals("false")) {

                return FsResponseGen.failMsg("您没有权限禁言该群组成员");
            }

            String groupId = request.getGroupId();
            String minute = request.getMinute();
            if (StringUtils.isBlank(minute)) {
                // 代表永久禁言
                minute = "0";
            }

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("userId", userId));
            params.add(new BasicNameValuePair("groupId", groupId));
            params.add(new BasicNameValuePair("minute", minute));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
             return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
             log.error("禁言指定群成员失败！", e.getMessage());
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 取消指定群成员禁言
     * @return
     */
    @RequestMapping("user/gag/rollback")
    @ResponseBody
    public FsResponse rollbackGagUser(@RequestBody GroupGagUserRequest request) {
        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("group/user/gag/rollback");

            String userId = request.getUserId();

            if (StringUtils.isBlank(userId)) {
                return FsResponseGen.failMsg("参数错误，userId为NULL");
            }

            String groupId = request.getGroupId();
            Long decodeGroupId = N3d.decode(request.getGroupId());

            String path = imUri + "group/hasManagerRole";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("groupId", decodeGroupId);
            jsonObject.put("memberId", getUserId());
            jsonObject.put("memberId3", "");
            jsonObject.put("memberId4", "2444");
             String resp = OKHttpUtil.httpPostJson(path, jsonObject.toJSONString(), commonHeader());

            JSONObject fsResponse = JSONObject.parseObject(resp);
            String code = fsResponse.getString("code");
            String result = fsResponse.getString("result");

            if (!"200".equals(code)){
                String msg = fsResponse.getString("message");

                return FsResponseGen.failMsg(msg);
            }
            if (result.equals("false")) {

                return FsResponseGen.failMsg("您没有权限");
            }

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("userId", userId));
            params.add(new BasicNameValuePair("groupId", groupId));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("取消指定群成员禁言失败！", e.getMessage());
        }
        return FsResponseGen.gen(false);
    }


    /**
     * 查询群成员禁言列表
     * @return
     */
    @RequestMapping("user/gag/list")
    @ResponseBody
    public FsResponse GagUserList (@RequestBody GroupGagUserRequest request) {
        try {
            HttpPost httpPost = rongCloudApplication.imConstructor("group/user/gag/list");

            String groupId = request.getGroupId();

            // 设置请求消息体参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("groupId", groupId));
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

            String response = rongCloudApplication.executeReq(httpPost);

            // 需要处理往APP端返回的userId, 以及增加用户的头像和昵称
            GroupGagUserDto dto = JSON.parseObject(response, GroupGagUserDto.class);
            Integer code = dto.getCode();

            if (200 == code) {
                List<GroupGagUserDto.User> userList = new ArrayList<>();

                List<GroupGagUserDto.User> users = dto.getUsers();
                for (GroupGagUserDto.User userDto : users) {
                    String userId = userDto.getUserId();
                    if (StringUtils.isNotBlank(userId)) {
                        userId = String.valueOf(N3d.decode(userId));
                    }
                    // 查询用户的头像和昵称
                    User user = userService.selectById(Long.valueOf(userId));
                    if (null != user) {
                        userDto.setAvatar(user.getAvatar());
                        userDto.setNick(user.getNick());
                    }
                    userList.add(userDto);
                }

                dto.setUsers(userList);
                response = JSON.toJSONString(dto);
            }

            // 解析响应数据
            return rongCloudApplication.judgmentResults(response);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询群成员禁言列表失败！", e.getMessage());
        }
        return FsResponseGen.gen(false);
    }

    /**
     * 查询社群列表
     * @return
     */
    @RequestMapping("queryAssociationList")
    @ResponseBody
    public FsResponse queryAssociationList () {

        Long userId = getUserId();
        ArrayList<GroupManageDto> groupManageList = new ArrayList<>();

        List<GroupManage> list = groupService.queryAssociationList();
        for (GroupManage manage : list) {
            GroupManageDto dto = new GroupManageDto();
            BeanUtils.copyProperties(manage, dto);

            Integer groupId = manage.getGroupId();
            RcGroupMembers groupMembers = groupService.selectGroupMember(groupId, userId);
            if (groupMembers == null || groupMembers.getIsdeleted()) {
                dto.setState(GroupManageDto.JOINED_NO);
            }
            else {
                dto.setState(GroupManageDto.JOINED_YES);
            }
            groupManageList.add(dto);
        }
        return FsResponseGen.successData(groupManageList);
    }

//    @PostMapping("/user/list")
//    public FsResponse list(@RequestBody GroupUserListRequest params) {
//        params.valid();
//        FsPage page = FsPage.init(params.getPageNo(), params.getPageSize());
//        FsResponse copy = groupService.selectUserList(page,getUserId(), params.getGroupId());
//
//        FsGroupResponse res = new FsGroupResponse();
//        res.setGroupId(params.getGroupId());
//        res.setCount(copy.getCount());
//        res.setPageSize(copy.getPageSize());
//        res.setPageNo(copy.getPageNo());
//        res.setMsg(copy.getMsg());
//        res.setCode(copy.getCode());
//        res.setData(copy.getData());
//        res.setSuccess(copy.isSuccess());
//
//        return res;
//    }
//
//
//    /**
//     * 信息
//     */
//    @PostMapping("/info")
//    public FsResponse info(@RequestBody GroupInfoRequest params) {
//        params.valid();
//
//        //群基本信息
//
//        RcGroups group = groupService.selectById(params.getGroupId());
//        Contracts.assertNotNull(group, YiChatMsgCode.GROUP_INFO_NONE.msg());
//
//        GroupDto dto = new GroupDto();
//        dto.setGroupId(group.getId());
//        dto.setCrateUnixTime(group.getCreatedat().getTime());
//        dto.setGroupAvatar(group.getPortraituri());
////        dto.setGroupDescription(group.get());
////        dto.setVersion(String.valueOf(group.get()));
//        dto.setGroupSilentStatus(groupService.getGroupSilentStatus(params.getGroupId()));
//        dto.setGroupName(group.getName());
//        dto.setOwner(group.getCreatorid().longValue());
//        dto.setMemberCount(groupService.countMember(params.getGroupId()));
//        dto.setRoleType(getUserId().compareTo(dto.getOwner()) == 0 ? 2 : (groupService.isAdmin(params.getGroupId(), getUserId()) ? 1 : 0));
//
//        dto.setAdminList(groupService.selectAdminList(params.getGroupId()));
//        dto.setSilentList(groupService.selectSilentList(params.getGroupId()));
//        dto.setRoleType(groupService.selectRoleType(params.getGroupId(), getUserId()).getVal());
//        dto.setLastList(messageService.selecLastList(params.getGroupId(), getUserId(), params.getTimestamp()));
//        dto.setProtectStatus(groupService.selectProtectStatus(params.getGroupId()));
//
//        return FsResponseGen.successData(dto);
//    }
//
//
//    @PostMapping("/protect/status/set")
//    public FsResponse protectStatusSet(@RequestBody GroupProtectStatusRequest params) {
//
//        params.valid();
//        groupService.setProtectStatus(getUserId(), params.getGroupId(), params.getStatus());
//        return FsResponseGen.success();
//    }
//
//
//
//
//    /**
//     * 设置管理员
//     */
//    @PostMapping("/admin/set")
//    public FsResponse setAdmin(@RequestBody GroupAdminSetRequest params) {
//        params.valid();
//
//        Contracts.assertTrue(groupService.getCreator(params.getGroupId()).compareTo(getUserId()) == 0, YiChatMsgCode.GROUP_SET.msg());
//        GeneralUtils.splitExcludeEmpty(params.getUserIds()).forEach(v -> {
//            groupService.updateRoleType(Long.parseLong(v), params.getGroupId(), GroupRoleType.amdin,params.getStatus());
//        });
//        return FsResponseGen.success();
//    }
//
//    /**
//     * 管理员list
//     */
//    @PostMapping("/admin/list")
//    public FsResponse adminList(@RequestBody GroupAdminListRequest params) {
//        params.valid();
//        return FsResponseGen.successData(groupService.selectAdminList(params.getGroupId()));
//    }
//
//
//    /**
//     * 禁言设置/取消
//     */
//    @PostMapping("/silent/set")
//    public FsResponse silentSet(@RequestBody GroupSilentSetRequest params) {
//        params.valid();
//        groupService.updateSilentStatus(getUserId(), params.getGroupId(), 1,params.getStatus());
//        return FsResponseGen.success();
//    }
//
//
//    /**
//     * 群成员禁言设置/取消
//     */
//    @PostMapping("/member/silent/set")
//    public FsResponse memberSilentSet(@RequestBody GroupSilentSetRequest params) throws Exception {
//        params.valid();
//        groupService.updateSilentStatus(N3d.decode(params.getUserId()), params.getGroupId(), 0,params.getStatus());
//        return FsResponseGen.success();
//    }
//
//
//    /**
//     * 群禁言列表
//     */
//    @PostMapping("/silent/list")
//    public FsResponse silentList(@RequestBody GroupInfoRequest params) {
//        params.valid();
//
//        return FsResponseGen.successData(groupService.selectSilentList(params.getGroupId()));
//    }
//
//
//    /**
//     * 发布群公告
//     */
//    @PostMapping("/notice/publish")
//    public FsResponse noticePublish(@RequestBody GroupNoticeRequest params) {
//        params.valid();
//        appNoticeService.add(params.getTitle(), params.getContent(), getUserId(),params.getGroupId());
//        return FsResponseGen.successData(DtoChangeUtils.getList(appNoticeService.selectLastNotice(params.getGroupId()), v -> {
//            GroupNoticeDto dto = new GroupNoticeDto();
//            dto.setContent(v.getContent());
//            dto.setTitle(v.getTitle());
//            dto.setTime(v.getCtime().getTime());
//            dto.setNoticeId(v.getId());
//            dto.setTimeDesc(DateUtils.formatDate(v.getCtime()));
//
//            User user = userService.selectById(v.getUserId());
//            dto.setAvatar(user.getAvatar());
//            dto.setUserId(v.getUserId());
//            dto.setTitle(v.getTitle());
//            return dto;
//        }));
//    }
//
//    /**
//     * 获取最新公告
//     */
//    @PostMapping("/notice/last")
//    public FsResponse getNotice(@RequestBody GroupNoticeGetRequest params) {
//        params.valid();
//        return FsResponseGen.successData(DtoChangeUtils.getList(appNoticeService.selectLastNotice(params.getGroupId()), v -> {
//            GroupNoticeDto dto = new GroupNoticeDto();
//            dto.setContent(v.getContent());
//            dto.setTitle(v.getTitle());
//            dto.setTime(v.getCtime().getTime());
//            dto.setTimeDesc(DateUtils.formatDate(v.getCtime()));
//
//            User user = userService.selectById(v.getUserId());
//            dto.setAvatar(user.getAvatar());
//            dto.setUserId(v.getUserId());
//            dto.setTitle(v.getTitle());
//            dto.setNoticeId(v.getId());
//            return dto;
//        }));
//    }
//
//    /**
//     * 删除公告
//     */
//    @PostMapping("/notice/delete")
//    public FsResponse deleteNotice(@RequestBody GroupNoticeDeleteRequest params) {
//        params.valid();
//        appNoticeService.deleteNotice(params.getNoticeId());
//        return FsResponseGen.success();
//
//    }
//
//    /**
//     * 群详细信息
//     */
//    @PostMapping("/detail")
//    public FsResponse detailGroup(@RequestBody GroupInfoRequest params) {
//
//        RcGroups group = groupService.selectById(params.getGroupId());
//        GroupDetailDto dto = new GroupDetailDto();
//        dto.setCreate_date(group.getCreationDate());
//        dto.setCreator(Long.parseLong(group.getCreator()));
//        dto.setName(group.getName());
//        dto.setGid(group.getGid());
//        dto.setImgurlde(group.getImgurl());
//        dto.setVersion(group.getVersion());
//        dto.setDesc(group.getDescri());
//        return FsResponseGen.successData(dto);
//    }
//
//    /**
//     * 我的群列表
//     */
//    @PostMapping("/my/list")
//    public FsResponse myGroupList() {
//
//        return FsResponseGen.successData(DtoChangeUtils.getList(groupService.selectMyGroupList(getUserId()), v -> {
//            GroupDetailDto dto = new GroupDetailDto();
//            dto.setCreate_date(v.getCreationDate());
//            dto.setCreator(Long.parseLong(v.getCreator()));
//            dto.setName(v.getName());
//            dto.setGid(v.getGid());
//            dto.setImgurlde(v.getImgurl());
//            dto.setVersion(v.getVersion());
//            dto.setDesc(v.getDescri());
//
//            return dto;
//        }));
//    }
//
//    /**
//     * 我是群主的群列表
//     */
//    @PostMapping("/owner/list")
//    public FsResponse ownerList() {
//
//        return FsResponseGen.successData(DtoChangeUtils.getList(groupService.selectMyOwnerList(getUserId()), v -> {
//            GroupDetailDto dto = new GroupDetailDto();
//            dto.setCreate_date(v.getCreationDate());
//            dto.setCreator(Long.parseLong(v.getCreator()));
//            dto.setName(v.getName());
//            dto.setGid(v.getGid());
//            dto.setImgurlde(v.getImgurl());
//            dto.setVersion(v.getVersion());
//            dto.setDesc(v.getDescri());
//
//            return dto;
//        }));
//    }
//

//    /**
//     * 退群
//     */
//    @PostMapping("/quit")
//    public FsResponse quit(@RequestBody GroupQuitRequest request) {
//        request.valid();
//        packetService.quitGroupSale(getUserId(), request.getGroupId());
//        return FsResponseGen.success();
//    }

    private Map<String, String> commonHeader() {
        Map<String, String> result = new HashMap<>();
        result.put("None-AES", "1");
        result.put("Content-Type", "application/json");
        result.put("Authorization", "Basic YWRtaW5AYXBwLmltOjEyMzQ1NkBhcHA=");
        return result;
    }
}
